<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

include_once('../arc2-starter-pack/config.php');
$store = ARC2::getStore($arc_config);

$output = array();


$q = "
prefix dct:<http://purl.org/dc/terms/>
prefix xsd:<http://www.w3.org/2001/XMLSchema#>
select distinct ?creator ?paper where{
	?paper dct:creator <".$_GET["uri"].">.
	?paper dct:creator ?creator.
	?paper dct:date ?date.
	filter regex(?date,'".$_GET["date"]."')
}";

$rows = $store->query($q, 'rows');

foreach ($rows as $row) {
	$uri = $row["creator"];
	if (isset($output["people"][$uri])) {
		$output["people"][$uri]["count"]++;
	}
	else {	
		$person = array();
		$person["count"] = 1;
		$person["name"] = $uri;
		$person["longName"] = "";
		$output["people"][$uri] = $person;
	}
}

$q = "
prefix foaf:<http://xmlns.com/foaf/0.1/>
prefix dct:<http://purl.org/dc/terms/>
prefix xsd:<http://www.w3.org/2001/XMLSchema#>
select distinct ?creator ?name where {
	?paper dct:creator <".$_GET["uri"].">.
	?paper dct:creator ?creator.
	?paper dct:date ?date.
	?creator foaf:name ?name.
	filter regex(?date,'".$_GET["date"]."')
}";
$rows = $store->query($q, 'rows');

foreach ($rows as $row) {
	$uri = $row["creator"];
	$name = $row["name"];
	if (strlen($output["people"][$uri]["name"]) > strlen($name)) {
		$output["people"][$uri]["name"] = $name;
	}
	if (strlen($output["people"][$uri]["longName"]) < strlen($name)) {
		$output["people"][$uri]["longName"] = $name;
	}
}

# deal with any person who hasn't got a real name - you guys SUCK
foreach($output["people"] as $uri => $p) {
	if ($p["name"] == $uri) {
//		$output["people"][$uri]["name"] = "?";
//		$output["people"][$uri]["longName"] = "unknown author";
		unset($output["people"][$uri]);
	}	
}



# remove the subject
$output["uri"] = $_GET["uri"];
$output["name"] = $output["people"][$_GET["uri"]]["name"];
$output["longName"] = $output["people"][$_GET["uri"]]["longName"];
unset($output["people"][$_GET["uri"]]);



# output as json
header('Content-type: text/plain');
echo json_encode($output);

?>
